#!/bin/sh
# Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

### BEGIN INIT INFO
# Provides:          chameleon-updater
# Required-Start:    $network $remote_fs
# Required-Stop:     $network $remote_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start chameleon-updater at boot time
# Description:       Auto-update chameleond by checking any new version in
#                    the Google Cloud Storage and installing it.
### END INIT INFO

UPDATER_NAME='chameleon-updater'
DAEMON_NAME='chameleond'
CONFIG_FILE="/etc/default/${DAEMON_NAME}"
. "${CONFIG_FILE}"

MIRROR_URL='http://commondatastorage.googleapis.com/chromeos-localmirror'
BUNDLE_PATH='distfiles/chameleon-bundle'
BUNDLE_URL="${MIRROR_URL}/${BUNDLE_PATH}"

get_ver () {
    # chameleond-0.0.1-r2.tar.gz -> 0.0.1
    local name=$1
    local ver=${name%-r*}
    local ver=${ver#*-}
    echo ${ver}
}

get_rev () {
    # chameleond-0.0.1-r2.tar.gz -> 2
    local name=$1
    local rev=${name%.tar.gz}
    local rev=${rev##*-r}
    echo ${rev}
}

do_start () {
    echo 'Checking Chameleon update...'
    local latest_bundle=$(wget -qO - "${BUNDLE_URL}/LATEST")
    if [[ -z ${latest_bundle} ]] ; then
        echo 'Failed to get the LATEST bundle.'
        exit
    fi

    local bundle_dir=${latest_bundle%%-r*}
    local current_ver=$(get_ver ${BUNDLE_VERSION})
    local current_rev=$(get_rev ${BUNDLE_VERSION})
    local latest_ver=$(get_ver ${latest_bundle})
    local latest_rev=$(get_rev ${latest_bundle})
    if [[ "${current_ver}" > "${latest_ver}" ]] ; then
        echo 'No new update.'
        exit
    fi
    if [[ "${current_ver}" = "${latest_ver}" ]] ; then
        if [[ ${current_rev} -ge ${latest_rev} ]] ; then
            echo 'No new update.'
            exit
        fi
    fi

    echo "Update Chameleon daemon:" \
            "${current_ver}-r${current_rev} -> ${latest_ver}-r${latest_rev}"
    pushd /tmp > /dev/null
    wget -q "${BUNDLE_URL}/${latest_bundle}"
    tar zxf ${latest_bundle}
    cd ${bundle_dir}
    make install \
        BUNDLE_VERSION="${latest_ver}-r${latest_rev}" \
        CHAMELEON_BOARD="${CHAMELEON_BOARD}"
    popd > /dev/null
}

do_stop () {
    echo 'do nothing'
}

case "$1" in
    start|stop)
        do_${1}
        ;;

    restart)
        do_stop
        do_start
        ;;

    *)
        echo "Usage: /etc/init.d/${UPDATER_NAME} {start|stop|restart}"
        exit 1
        ;;
esac
exit 0
